package com.lzxuni.common.utils.web;

import com.lzxuni.common.utils.StringUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *  http 发送接口工具类，本工具类基于 spring RestTemplate 实现，如果接口支持rest API，接口使用请参考 RestTemplate 使用即可<br>
 *
 * @author:孙志强
 * @create:2019-01-24 20:42
 * @Modified BY:
 **/

public class RestTemplateUtils {
	public static <T> T get(String url, Class<T> responseType, Map<String, ?> uriVariables) {
		return exchange(url, HttpMethod.GET,responseType, uriVariables,null, null);
	}
	public static <T> T getForEntity(String url, Class<T> responseType, Object request) {
		return exchange(url, HttpMethod.GET,responseType, null,request, null);
	}
	public static <T> T post(String url, Class<T> responseType, Map<String, ?> uriVariables) {
		return exchange(url, HttpMethod.POST,responseType, uriVariables,null, null);
	}
	public static <T> T postForEntity(String url, Class<T> responseType, Object request) {
		return exchange(url, HttpMethod.POST,responseType, null,request, null);
	}


	private RestTemplate getRestTemplate() {

		OkHttp3ClientHttpRequestFactory okHttp3ClientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory();
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
		return restTemplate;
	}
	public static <T> T exchange(String url, HttpMethod method,Class<T> responseType, Map<String, ?> uriVariables,Object request, Map<String, String> headers) {
		HttpHeaders requestHeaders = new HttpHeaders();
		if (!CollectionUtils.isEmpty(requestHeaders)) {
//			requestHeaders.setContentType(MediaType.APPLICATION_JSON);

			Iterator<Map.Entry<String, String>> iter = headers.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<String, String> entry = iter.next();
				requestHeaders.set(entry.getKey(), entry.getValue());
			}
		}
		Map beanMap = new HashMap();
		if (request != null) {
			try {
				beanMap = BeanUtils.describe(request);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (!CollectionUtils.isEmpty(uriVariables)) {
			uriVariables.putAll(beanMap);
		}else{
			uriVariables = beanMap;
		}
		if (!CollectionUtils.isEmpty(uriVariables)) {
			String s = new RestTemplateUtils().buildMap(uriVariables);
			url = url + "?" + s;
		}
		RestTemplate template = new RestTemplateUtils().getRestTemplate();
		HttpEntity<Object> requestEntity = new HttpEntity<>(request, requestHeaders);
		ResponseEntity<T> response = template.exchange(url, method, requestEntity, responseType);
		return response.getBody();
	}


	private String buildMap(Map<String, ?> map) {
		StringBuffer sb = new StringBuffer();
		if (!CollectionUtils.isEmpty(map)) {
			for (String key : map.keySet()) {

				if (StringUtils.isNotEmpty((String)map.get(key))) {
					String value = (String) map.get(key);
					sb.append(key + "="+value + "&");
//					try {
//						value = URLEncoder.encode(value, "UTF-8");
//					} catch (UnsupportedEncodingException e) {
//						e.printStackTrace();
//					}
				}
			}
		}
		return sb.toString();
	}
}
